//
//  XPPictureDisplayView.swift
//  SinaWeibo
//
//  Created by 徐攀 on 16/5/19.
//  Copyright © 2016年 徐攀. All rights reserved.
//

import UIKit

let pictureDisplayViewId = "pictureDisplayViewId"

class XPPictureDisplayView: UICollectionView {
    
    var didSelectedAddImageItem:(()->())?
    
    var images: [UIImage] = [UIImage]() {
        didSet {
            if images.count > 9 {
                return
            }
            images.count == 0 ? (hidden = true) : (hidden = false)
            reloadData()
        }
    }

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        backgroundColor = UIColor.whiteColor()
        hidden = true
        dataSource = self
        delegate = self
        registerClass(XPPicChooseCell.self, forCellWithReuseIdentifier: pictureDisplayViewId)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        x = 10
        y = 100
        width = screenWidth - 20
        height = width
        
        let cellMargin: CGFloat = 5
        let itemWidth = (width - 2 * cellMargin) / 3
        
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        flowLayout.minimumInteritemSpacing = cellMargin
        flowLayout.minimumLineSpacing = cellMargin
        flowLayout.itemSize = CGSizeMake(itemWidth, itemWidth)
    }
}

// MARK: - UICollectionViewDataSource
extension XPPictureDisplayView: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if images.count == 0 || images.count == 9 {
            return images.count
        }else {
            return images.count + 1
        }
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureDisplayViewId, forIndexPath: indexPath) as! XPPicChooseCell
        
        if indexPath.row < images.count {
            cell.image = images[indexPath.item]
            cell.deleteThePicture = { [weak self] in
                self?.images.removeAtIndex(indexPath.item)
                self?.reloadData()
            }
            
        }else {
            cell.image = nil
        }
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        collectionView.deselectItemAtIndexPath(indexPath, animated: true)
        
        if indexPath.row == images.count {
            didSelectedAddImageItem?()
        }
    }
}

/// 自定义Cell
class XPPicChooseCell: UICollectionViewCell {
    
    var deleteThePicture:(()->())?
    
    private lazy var myPicture: UIImageView = {
        let imageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        imageView.contentMode = .ScaleAspectFill
        imageView.clipsToBounds = true
        return imageView
    }()
    
    private lazy var deleteButton: UIButton = {
        let deleteButton = UIButton()
        deleteButton.addTarget(self, action: #selector(XPPicChooseCell.deleteButtonClick), forControlEvents: .TouchUpInside)
        deleteButton.setImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        deleteButton.hidden = true
        deleteButton.sizeToFit()
        return deleteButton
    }()
    
    @objc private func deleteButtonClick() {
        deleteThePicture?()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        addSubview(myPicture)
        addSubview(deleteButton)
        myPicture.frame = contentView.bounds
        
        deleteButton.snp_makeConstraints { (make) -> Void in
            make.trailing.equalTo(contentView)
            make.top.equalTo(contentView)
        }
    }
    
    // 被选择要发布的图片
    var image: UIImage? {
        didSet {
            if image == nil {
                myPicture.image = UIImage(named: "compose_pic_add")
                myPicture.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                deleteButton.hidden = true
            } else {
                myPicture.image = image
                myPicture.highlightedImage = nil
                deleteButton.hidden = false
            }
        }
    }
    

}


